package cn.iocoder.yudao.module.reading.dal.mysql.community;

import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.reading.dal.dataobject.community.CommunityDraftDO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Delete;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 社区草稿 Mapper
 *
 * @author 芋道源码
 */
@Mapper
public interface CommunityDraftMapper extends BaseMapperX<CommunityDraftDO> {

    /**
     * 查询用户最新的草稿
     */
    default CommunityDraftDO selectLatestByUserIdAndType(Long userId, String type) {
        return selectOne(new LambdaQueryWrapperX<CommunityDraftDO>()
                .eq(CommunityDraftDO::getUserId, userId)
                .eq(CommunityDraftDO::getType, type)
                .orderByDesc(CommunityDraftDO::getUpdateTime)
                .last("LIMIT 1"));
    }

    /**
     * 查询过期的草稿
     */
    default List<CommunityDraftDO> selectExpiredDrafts() {
        return selectList(new LambdaQueryWrapperX<CommunityDraftDO>()
                .lt(CommunityDraftDO::getExpireTime, LocalDateTime.now()));
    }

    /**
     * 删除用户指定类型的所有草稿（逻辑删除）
     */
    default void deleteByUserIdAndType(Long userId, String type) {
        delete(new LambdaQueryWrapperX<CommunityDraftDO>()
                .eq(CommunityDraftDO::getUserId, userId)
                .eq(CommunityDraftDO::getType, type));
    }

    /**
     * 物理删除用户指定类型的所有草稿
     * 用于发布动态后彻底删除草稿数据
     */
    @Delete("DELETE FROM community_drafts WHERE user_id = #{userId} AND type = #{type}")
    void physicalDeleteByUserIdAndType(@Param("userId") Long userId, @Param("type") String type);

    /**
     * 物理删除过期的草稿（批量）
     * 用于定时任务清理过期草稿
     */
    @Delete("DELETE FROM community_drafts WHERE expire_time < #{expireTime}")
    void physicalDeleteExpiredDrafts(@Param("expireTime") LocalDateTime expireTime);

}
